<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\AgentWebsiteLetter;
use App\Models\WebsiteLetter;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class WebsiteLetterController extends Controller
{
    public function list(Request $request)
    {
        return $this->response->array(
            WebsiteLetter::query()
                ->when($request->get('title'), function (Builder $query, $title) {
                    $query->where('title', 'like', "%$title%");
                })
                ->when($request->get('created_at_begin'), function (Builder $query, $createdAtBegin) {
                    $query->where('created_at', '>=', $createdAtBegin);
                })
                ->when($request->get('created_at_end'), function (Builder $query, $createdAtEnd) {
                    $query->where('created_at', '<=', Carbon::parse($createdAtEnd)->endOfDay());
                })
                ->with('attachments')
                ->paginate()
        );
    }

    public function store(Request $request)
    {
        $webSiteLetter = null;
        DB::transaction(function () use ($request, &$webSiteLetter) {
            $webSiteLetter = WebsiteLetter::query()->create(
                $request->only(['title', 'content', 'range_type', 'link']));

            if ($webSiteLetter->range_type === WebsiteLetter::RANGE_TYPE_DESIGNATED) {
                $webSiteLetter->agentLetter()->createMany(array_map(function ($agentId) {
                    return [
                        'agent_id' => $agentId,
                    ];
                }, Agent::query()
                    ->whereIn('phone', explode(',', $request->get('designated_member')))
                    ->pluck('id')
                    ->toArray()));
            }

            $webSiteLetter->attachments()->sync($request->get('pic', []));
            $attachment = $request->get('attachment', []);
            $temp = [];
            foreach ($attachment as $attachmentId) {
                $temp[$attachmentId] = ['type' => WebsiteLetter::ATTACHMENT_TYPE_FILE];
            }
            $webSiteLetter->attachments()->syncWithoutDetaching($temp); // 文件附件, 这里用 syncWithoutDetaching 不清除上面的图片 ID
        });

        return $this->response->created(null, $webSiteLetter);
    }

    public function update(Request $request)
    {
        $webSiteLetter = null;
        DB::transaction(function () use ($request, &$webSiteLetter) {
            $webSiteLetter = WebsiteLetter::query()->findOrFail($request->id);

            $haveReadAgentIds = [];
            if ($webSiteLetter->range_type === WebsiteLetter::RANGE_TYPE_DESIGNATED) {
                // 找出已读的站内信
                $haveReadAgentIds = $webSiteLetter
                    ->agentLetter()
                    ->where('status', AgentWebsiteLetter::STATUS_HAVE_READ)
                    ->pluck('agent_id')
                    ->toArray();
                $webSiteLetter->agentLetter()->delete(); // 删除站内信
            }
            if ($request->get('range_type') === WebsiteLetter::RANGE_TYPE_DESIGNATED) {
                // 重新写入
                $webSiteLetter->agentLetter()->createMany(
                    Agent::query()
                        ->whereIn('phone', explode(',', $request->get('designated_member')))
                        ->pluck('id')
                        ->map(function ($agentId) use ($haveReadAgentIds) {
                            return [
                                'agent_id' => $agentId,
                                'status' => in_array((int) $agentId, $haveReadAgentIds, true) ? AgentWebsiteLetter::STATUS_HAVE_READ : AgentWebsiteLetter::STATUS_UNREAD
                            ];
                        })
                );
            }

            $webSiteLetter->attachments()->sync($request->get('pic', []));
            $attachment = $request->get('attachment', []);
            $temp = [];
            foreach ($attachment as $attachmentId) {
                $temp[$attachmentId] = ['type' => WebsiteLetter::ATTACHMENT_TYPE_FILE];
            }
            $webSiteLetter->attachments()->syncWithoutDetaching($temp); // 文件附件, 这里用 syncWithoutDetaching 不清除上面的图片 ID

            $webSiteLetter->update($request->only(['title', 'content', 'range_type', 'link']));
        });

        return $this->response->created(null, $webSiteLetter);
    }

    public function delete($id)
    {
        DB::transaction(function () use ($id) {
            $websiteLetter = WebsiteLetter::query()->findOrFail($id);
            $websiteLetter->delete();
            $websiteLetter->agentLetter()->delete();
        });

        return $this->response->noContent();
    }

    public function info($id)
    {
        return $this->response->array(
            WebsiteLetter::query()
                ->with(['attachments', 'agentLetter' => function (HasMany $agentLetter) {
                    $agentLetter->with(['agent:id,phone']);
                }])
                ->findOrFail($id)
                ->toArray()
        );
    }
}
